#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/fs.h"
#include "kernel/param.h"

int
find(char *path, char *name)
{
  char fpath[MAXPATH];
  int fd;
  struct stat st;
  struct dirent de;
  if((fd = open(path, 0)) < 0){
    fprintf(2, "find: cannot open %s\n", path);
    close(fd);
    return 1;
  }
  strcpy(fpath, path);
  char * strp = fpath+strlen(fpath);
  *strp = '/';
  strp++;
  while(read(fd, &de, sizeof(de)) == sizeof(de)){
    if(de.inum == 0)
      break;
    if( strcmp(de.name, ".") == 0 ||
      strcmp(de.name, "..") == 0)
      continue;
    if(strlen(path)+strlen(name) >= MAXPATH-1) // path too long
      continue;
    int i = 0;
    do{
      strp[i] = de.name[i];
    }while(de.name[i++]);
    fpath[MAXPATH-1] = '\0';

    if(strcmp(name, de.name) == 0)
      printf("%s\n", fpath);
    
    if(stat(fpath, &st) == 0
      && st.type == T_DIR){
      find(fpath, name);
    }
  }
  return 0;
}

int
main(int argc, char *argv[])
{
  char spath[MAXPATH];
  char sname[DIRSIZ+1];
  struct stat st;
  if(argc == 3){
    if(strlen(argv[1]) >= MAXPATH){
      fprintf(2, "find: path %s is too long\n", argv[1]);
      exit(1);
    }
    strcpy(spath,argv[1]);
    // FIXME: sname length limit
    strcpy(sname, argv[2]);
  }else if(argc == 2){
    strcpy(spath, ".");
    strcpy(sname, argv[1]);
  }else {
    fprintf(2, "bad usage\n");
    exit(1);
  }
  if(stat(spath, &st) < 0 || st.type != T_DIR){
    fprintf(2, "find: %s is not dir\n", spath);
    exit(1);
  }
  if(find(spath, sname) == 0)
    exit(0);
  else
    exit(1);
}
